﻿using System;
using System.Runtime.CompilerServices;
using System.Threading;

namespace RaisingStudio.SmallProgram.Library
{
    [SmallProgramType]
    public static class Timer
    {
        public const int _maxInterval = 100000000;
        private static int _interval = _maxInterval;

        private static System.Threading.Timer _threadTimer = new System.Threading.Timer(new TimerCallback(Timer.ThreadTimerCallback));
        
        private static  event SmallProgramCallback _tick;
        public static  event SmallProgramCallback Tick
        {
            add
            {
                _tick = null;
				_tick += value;
            }
            remove
            {
                _tick -= value;
            }
        }

        public static void Pause()
        {
            _threadTimer.Change(-1, -1);
        }

        public static void Resume()
        {
            _threadTimer.Change(_interval, _interval);
        }

        private static void ThreadTimerCallback(object tag)
        {
            if (_tick != null)
            {
                _tick();
            }
        }

        public static Primitive Interval
        {
            get
            {
                return _interval;
            }
            set
            {
                _interval = (int)value;
                _interval = (int)Math.Max(10, Math.Min(_interval, _maxInterval));
                _threadTimer.Change(_interval, _interval);
            }
        }
    }
}

